package com.example.demo.demoApi.apiHandler;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * api处理器路由
 */
@Component
public class ApiSelector implements ApplicationContextAware {
    /**
     * 消息类名称和类对应Map
     */
    private Map<String, Class> requestMsgClassMap;

    /**
     * 消息类和处理类对应Map
     */
    private Map<Class, ApiMsgTypeHandler> handlerMap;

    /**
     * 根据class获取一个处理类
     * @param clazz 消息类
     * @return 处理该消息的类
     */
    public ApiMsgTypeHandler selectApiHandler(Class clazz){
        if (null == handlerMap || handlerMap.isEmpty()){
            throw new IllegalArgumentException("handler map is empty!");
        }
        return handlerMap.get(clazz);
    }

    /**
     * 根据消息类名称获取该消息类型
     * @param clazzName 类名称
     * @return 类
     */
    public Class selectMsgClass(String clazzName){
        if (null == requestMsgClassMap || requestMsgClassMap.isEmpty()){
            throw new IllegalArgumentException("msg map is empty!");
        }
        return requestMsgClassMap.get(clazzName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ApiMsgTypeHandler> handlerBeansMap =  applicationContext.getBeansOfType(ApiMsgTypeHandler.class);
        if (null == handlerBeansMap || handlerBeansMap.isEmpty()){
            return;
        }
        handlerMap = new HashMap<>(handlerBeansMap.size());
        requestMsgClassMap = new HashMap<>(handlerBeansMap.size());
        for (ApiMsgTypeHandler handler : handlerBeansMap.values()) {
            handlerMap.put(handler.getHandleMsgType(), handler);
            requestMsgClassMap.put(handler.getHandleMsgType().getSimpleName(), handler.getHandleMsgType());
        }
    }
}
